import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getPosts } from '../api/forum'

export interface ForumPost {
  id: number
  title: string
  author: string
  authorId: number
  authorAvatar?: string
  likes: number
  commentCount: number
  time: string
  category: string
  categoryId: number
  content: string
}

export const useForumStore = defineStore('forum', () => {
  const posts = ref<ForumPost[]>([])
  const loading = ref(false)
  const error = ref<string | null>(null)

  // 获取所有帖子，支持 categoryId
  async function fetchPosts(page = 1, size = 10, categoryId?: number) {
    loading.value = true
    error.value = null
    try {
      const params: any = {
        page,
        size,
        userType: 0
      }
      if (categoryId !== undefined && categoryId !== -1) {
        params.categoryId = categoryId
      }
      const data = await getPosts(params)
      console.log('fetchPosts 后端返回：', data)
      if ((data && (data.code === 0 || data.code === 200)) && data.data && Array.isArray(data.data.records)) {
        posts.value = data.data.records.map((item: any) => ({
          id: item.id,
          title: item.title,
          author: item.authorNickname || String(item.authorId),
          authorId: item.authorId,
          authorAvatar: item.authorAvatar,
          likes: item.likeCount ?? 0,
          commentCount: item.commentCount ?? 0,
          time: item.createTime,
          category: item.categoryName || '其他',
          categoryId: item.categoryId,
          content: item.content || '',
        }))
        console.log('posts.value', posts.value)
        return {
          total: data.data.total,
          totalPages: data.data.totalPages,
          pageNum: data.data.pageNum,
          pageSize: data.data.pageSize
        }
      } else {
        throw new Error((data && data.message) || '获取帖子失败')
      }
    } catch (e: any) {
      error.value = e.message || '获取帖子失败'
      return null
    } finally {
      loading.value = false
    }
  }

  return { posts, loading, error, fetchPosts }
})
